import {designPage, Fragment, reactive, useRefs} from "@peryl/react-compose";
import {Alert, ArrowStep, ArrowStepGroup, Box, Button, Form, FormInput, FormItem, i18n, Icon, Input, InputGroup, PageCard, PageCardContent, PageCardTitle, PageThemeUtils, RollingNumber, Select, SelectOption, Space} from "plain-design";
import './step-form-page.scss';
import {delay} from "@peryl/utils/delay";

export default designPage(() => {

  const { refs, onRef } = useRefs({ form: Form });

  const state = reactive({
    currentStep: 0,
    formData: {
      paymentAccount: '@peryl/micro-web',
      receiptAccount: 'martsforever@peryl.com',
      receiptWay: 'weixin',
      receiptTime: 'delay',
      receiptName: '痞老板很pi',
      receiptAmount: '1314',
      paymentPassword: '123456',
    } as any,
  });

  const receiptWayOptions: { name: string, val: string }[] = [
    { name: i18n.$intl('page.stepFormPage.receiptWayOptions.0').d('微信'), val: 'weixin' },
    { name: i18n.$intl('page.stepFormPage.receiptWayOptions.1').d('支付宝'), val: 'alipay' },
    { name: i18n.$intl('page.stepFormPage.receiptWayOptions.2').d('银联'), val: 'yinlian' },
  ];
  const receiptTimeOptions: { name: string, val: string }[] = [
    { name: i18n.$intl('page.stepFormPage.receiptTimeOptions.0').d('定时转账'), val: 'delay' },
    { name: i18n.$intl('page.stepFormPage.receiptTimeOptions.1').d('立即转账'), val: 'immediate' },
  ];

  const steps: { title: string, render: () => any, buttons?: (prevButton: any) => any }[] = [
    {
      title: i18n.$intl('page.stepFormPage.TransferApplication').d('转账申请'),
      render: () => {
        return (
          <>
            <FormInput label={i18n.$intl('page.stepFormPage.paymentAccount').d("付款账户")} v-model={state.formData.paymentAccount} required/>
            <FormItem label={i18n.$intl('page.stepFormPage.receiptAccount').d("收款账户")} field="receiptAccount" required>
              <InputGroup>
                <Select width={90} noClear v-model={state.formData.receiptWay}>{receiptWayOptions.map(i => <SelectOption key={i.val} label={i.name} val={i.val}/>)}</Select>
                <Input v-model={state.formData.receiptAccount}/>
                <Select width={110} noClear v-model={state.formData.receiptTime}>{receiptTimeOptions.map(i => <SelectOption key={i.val} label={i.name} val={i.val}/>)}</Select>
              </InputGroup>
            </FormItem>
            <FormInput label={i18n.$intl('page.stepFormPage.receiptName').d("收款人名称")} v-model={state.formData.receiptName} required/>
            <FormInput label={i18n.$intl('page.stepFormPage.receiptAmount').d("收款金额")} v-model={state.formData.receiptAmount} required/>
          </>
        );
      },
    },
    {
      title: i18n.$intl('page.stepFormPage.TransferConfirmation').d('转账确认'),
      render: () => {
        return <>
          <Box className="mt padding" style={{ backgroundColor: PageThemeUtils.variable('secondary-1'), border: `solid 1px ${PageThemeUtils.variable('border-color')}` }}>
            <Alert>
              {i18n.$intl('page.stepFormPage.confirmMessage').d('确认转账后，资金将直接打入对方账户，无法退回。')}
            </Alert>
            <FormItem labelAlign={'left'} contentAlign={"right"} label={i18n.$intl('page.stepFormPage.paymentAccount').d("付款账户")}>{state.formData.paymentAccount}</FormItem>
            <FormItem labelAlign={'left'} contentAlign={"right"} label={i18n.$intl('page.stepFormPage.receiptAccount').d("收款账户")}>{state.formData.receiptAccount}</FormItem>
            <FormItem labelAlign={'left'} contentAlign={"right"} label={i18n.$intl('page.stepFormPage.receiptName').d("收款人名称")}>{state.formData.receiptName}</FormItem>
            <FormItem labelAlign={'left'} contentAlign={"right"} label={i18n.$intl('page.stepFormPage.receiptAmount').d("收款金额")}>
              <span style={{ fontSize: '1.5em', color: PageThemeUtils.variable('error-6'), fontWeight: '600' }}>
                <RollingNumber val={state.formData.receiptAmount}/> ¥
              </span>
            </FormItem>
            <FormInput
              prefixIcon="pi-safe"
              noClear
              width={90}
              formAttrs={{ labelAlign: 'left', contentAlign: 'right' }}
              label={i18n.$intl('page.stepFormPage.paymentPassword').d("支付密码")}
              v-model={state.formData.paymentPassword}
              required
              type="password"
              nativeAttrs={{ autoComplete: 'off' }}
              validator={async ({ formData }) => {
                await delay(2000);
                if (formData?.paymentPassword != 123456) {
                  return i18n.$intl('page.stepFormPage.paymentPasswordValidateMessage').d('支付密码不正确！是123456');
                }
              }}/>
          </Box>
        </>;
      },
    },
    {
      buttons: () => null,
      title: i18n.$intl('page.stepFormPage.TransferResult').d('转账结果'),
      render: () => {
        return (
          <div className="demo-form-step-result">
            <div className="demo-form-step-result-status"><Icon icon="pi-check-circle-fill"/></div>
            <div className="demo-form-step-result-title">{i18n.$intl('page.stepFormPage.successTitle').d("转账成功")}</div>
            <div className="demo-form-step-result-description">{i18n.$intl('page.stepFormPage.successMessage').d("预计三分钟内到账")}</div>
            <Box className="my">
              <Space align="center" inlineBlock>
                <Button label={i18n.$intl('page.stepFormPage.checkBills').d("查看账单")}/>
                <Button label={i18n.$intl('page.stepFormPage.again').d("再转一笔")} mode="fill" onClick={() => state.currentStep = 0}/>
              </Space>
            </Box>
            <Box className="demo-form-step-result-table padding">
              <table>
                <tbody>
                <tr>
                  <td>{i18n.$intl('page.stepFormPage.paymentAccount').d("付款账户")}：</td>
                  <td>{state.formData.paymentAccount}</td>
                </tr>
                <tr>
                  <td>{i18n.$intl('page.stepFormPage.receiptAccount').d("收款账户")}：</td>
                  <td>{state.formData.receiptAccount}</td>
                </tr>
                <tr>
                  <td>{i18n.$intl('page.stepFormPage.receiptName').d("收款人名称")}：</td>
                  <td>{state.formData.receiptName}</td>
                </tr>
                <tr>
                  <td>{i18n.$intl('page.stepFormPage.receiptAmount').d("收款金额")}：</td>
                  <td>
                    <span style={{ fontSize: '1.5em', color: PageThemeUtils.variable('error-6'), fontWeight: '600' }}>
                      <RollingNumber val={state.formData.receiptAmount}/> ¥
                    </span>
                  </td>
                </tr>
                </tbody>
              </table>
            </Box>
          </div>
        );
      },
    },
  ];

  const handler = {
    prev: () => {state.currentStep > 0 && state.currentStep--;},
    next: async () => {
      await refs.form!.validate();
      state.currentStep < steps.length && state.currentStep++;
    },
  };

  return () => {
    return (
      <PageCard>
        <PageCardTitle title="分步表单"/>
        <PageCardContent>
          <ArrowStepGroup current={state.currentStep}>
            {steps.map(i => (
              <ArrowStep title={i.title} key={i.title}/>
            ))}
          </ArrowStepGroup>
          <Form
            ref={onRef.form}
            className="mt"
            modelValue={state.formData}
            style={{ textAlign: 'center' }}
            singleColumnContentWidth={450}
            validateMessagePosition="bottom-right"
            verticalLabel={false}
          >
            <Fragment key={state.currentStep}>
              {steps[state.currentStep].render()}
            </Fragment>
            <FormItem label={null} contentAlign="center" key={state.currentStep + 'button'}>
              <Space inlineBlock>
                {(() => {
                  const prevButton = <>
                    {state.currentStep > 0 && <Button label="上一步" onClick={handler.prev}/>}
                    {state.currentStep < steps.length && <Button label="下一步" onClick={handler.next} mode="fill"/>}
                  </>;
                  return !steps[state.currentStep].buttons ? prevButton : steps[state.currentStep].buttons!(prevButton);
                })()}
              </Space>
            </FormItem>
          </Form>
        </PageCardContent>
      </PageCard>
    );
  };
});
